import SwiftUI

struct ChatView: View {
    @ObservedObject var viewModel: ChatViewModel
    @Binding var showModelConfig: Bool
    @State private var messageText: String = ""
    @State private var scrollToBottom = false
    @State private var appearTrigger = false // 用于首次加载时触发滚动
    
    init(viewModel: ChatViewModel, showModelConfig: Binding<Bool>) {
        self.viewModel = viewModel
        self._showModelConfig = showModelConfig
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // 顶部标题
            HStack {
                Text(viewModel.currentSession.title)
                    .font(.headline)
                    .padding(.top, -3)
                
                Spacer()
                
                // 已移除齿轮按钮
            }
            .padding(.horizontal)
            .padding(.vertical, 2)
            .background(Color(red: 0.97, green: 0.97, blue: 0.97))
            .overlay(
                Rectangle()
                    .frame(height: 1)
                    .foregroundColor(Color.gray.opacity(0.3)),
                alignment: .bottom
            )
            
            // 聊天内容
            GeometryReader { geometry in
                ScrollViewReader { scrollView in
                    ScrollView {
                        VStack(spacing: 15) {
                            ForEach(viewModel.currentSession.messages) { message in
                                MessageBubble(message: message, screenWidth: geometry.size.width)
                                    .id(message.id)
                            }
                            // 底部空间用于滚动
                            Color.clear.frame(height: 1).id("bottomID")
                        }
                        .padding()
                    }
                    .background(Color.white)
                    .onChange(of: viewModel.currentSession.messages.count) { _ in
                        // 当消息数量变化时，滚动到底部
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            withAnimation {
                                scrollView.scrollTo("bottomID", anchor: .bottom)
                            }
                        }
                    }
                    // 添加最小高度和滚动指示器
                    .frame(maxWidth: .infinity)
                    .scrollIndicators(.visible)
                    .onAppear {
                        // 首次出现时，滚动到底部
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                            withAnimation {
                                scrollView.scrollTo("bottomID", anchor: .bottom)
                                appearTrigger = true
                            }
                        }
                    }
                    .onChange(of: appearTrigger) { _ in
                        // 首次出现的备用触发器
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                            withAnimation {
                                scrollView.scrollTo("bottomID", anchor: .bottom)
                            }
                        }
                    }
                }
            }
            .frame(minHeight: 400) // 设置最小高度确保有足够的显示空间
            
            // 错误消息显示
            if let errorMessage = viewModel.errorMessage {
                Text(errorMessage)
                    .foregroundColor(.red)
                    .padding()
            }
            
            // 底部输入区域
            VStack(spacing: 12) {
                // 功能按钮行
                HStack(spacing: 12) {
                    // 左侧功能按钮组
                    HStack(spacing: 12) {
                        // 上传文件按钮
                        Button(action: {
                            // 上传文件功能
                        }) {
                            Image(systemName: "doc.arrow.up")
                                .font(.system(size: 14))
                                .foregroundColor(.gray)
                        }
                        .frame(width: 28, height: 28)
                        .background(Color(red: 0.97, green: 0.97, blue: 0.97))
                        .cornerRadius(14)
                        
                        // 上传图片按钮
                        Button(action: {
                            // 上传图片功能
                        }) {
                            Image(systemName: "photo")
                                .font(.system(size: 14))
                                .foregroundColor(.gray)
                        }
                        .frame(width: 28, height: 28)
                        .background(Color(red: 0.97, green: 0.97, blue: 0.97))
                        .cornerRadius(14)
                        
                        // 联网搜索按钮
                        Button(action: {
                            // 联网搜索功能
                        }) {
                            Image(systemName: "globe")
                                .font(.system(size: 14))
                                .foregroundColor(.gray)
                        }
                        .frame(width: 28, height: 28)
                        .background(Color(red: 0.97, green: 0.97, blue: 0.97))
                        .cornerRadius(14)
                    }
                    
                    Spacer()
                    
                    // 模型选择按钮
                    Menu {
                        ForEach(AIModelType.allCases) { model in
                            Button(action: {
                                viewModel.setCurrentModel(model)
                            }) {
                                HStack {
                                    Text(model.displayName)
                                    if viewModel.currentModelType == model {
                                        Image(systemName: "checkmark")
                                    }
                                }
                            }
                        }
                    } label: {
                        HStack(spacing: 2) {
                            Image(systemName: "chevron.down")
                                .font(.system(size: 10))
                                .foregroundColor(.gray)
                            Text(viewModel.currentModelType.displayName)
                                .font(.system(size: 12))
                                .foregroundColor(.gray)
                        }
                        .padding(.horizontal, 8)
                        .padding(.vertical, 6)
                        .background(Color(red: 0.97, green: 0.97, blue: 0.97))
                        .cornerRadius(14)
                    }
                    
                    // 发送按钮
                    Button(action: {
                        sendMessage()
                    }) {
                        Image(systemName: "paperplane.fill")
                            .font(.system(size: 14))
                            .foregroundColor(.white)
                            .frame(width: 28, height: 28)
                            .background(Color.blue)
                            .cornerRadius(14)
                    }
                    .disabled(viewModel.isLoading)
                }
                .padding(.horizontal)
                .padding(.top, 8)
                
                // 输入框行
                ZStack(alignment: .leading) {
                    if messageText.isEmpty {
                        Text("在这里输入您的问题...")
                            .foregroundColor(.gray)
                            .padding(.leading, 16)
                            .padding(.top, 12)
                    }
                    
                    TextEditor(text: $messageText)
                        .padding(12)
                        .frame(minHeight: 100, maxHeight: 120)
                }
                .background(Color(red: 0.95, green: 0.95, blue: 0.95))
                .cornerRadius(20)
                .frame(minHeight: 100)
                .padding(.horizontal)
                .padding(.bottom, 8)
            }
            .background(Color.white)
            .overlay(
                Rectangle()
                    .frame(height: 1)
                    .foregroundColor(Color.gray.opacity(0.3)),
                alignment: .top
            )
        }
        .background(Color.white)
    }
    
    private func sendMessage() {
        guard !messageText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
        
        let message = messageText
        messageText = ""
        
        // 使用ViewModel发送消息，利用流式输出
        viewModel.sendMessage(message)
    }
}

struct MessageBubble: View {
    let message: ChatMessage
    let screenWidth: CGFloat
    
    var body: some View {
        HStack(alignment: .bottom) {
            if message.role == .user {
                Spacer(minLength: screenWidth * 0.05) // 减少间距以增加可用空间
                
                VStack(alignment: .trailing, spacing: 2) {
                    Text(message.content)
                        .padding(12)
                        .background(Color(red: 0.35, green: 0.55, blue: 0.85).opacity(0.9))
                        .foregroundColor(.white)
                        .font(.system(size: 15))
                        .multilineTextAlignment(.leading)
                        .fixedSize(horizontal: false, vertical: true)
                        .lineLimit(nil)
                        .cornerRadius(12)
                    
                    Text(getFormattedTime(from: message.timestamp))
                        .font(.caption2)
                        .foregroundColor(.gray)
                        .padding(.trailing, 2)
                        .padding(.top, 2)
                }
                .frame(maxWidth: min(screenWidth * 0.85, 700), alignment: .trailing) // 增加宽度比例和最大像素值
            } else if message.role == .assistant {
                VStack(alignment: .leading, spacing: 2) {
                    Text(message.content)
                        .padding(12)
                        .background(Color(red: 0.94, green: 0.94, blue: 0.94))
                        .foregroundColor(.black)
                        .font(.system(size: 15))
                        .multilineTextAlignment(.leading)
                        .fixedSize(horizontal: false, vertical: true)
                        .lineLimit(nil)
                        .cornerRadius(12)
                        .overlay(
                            Group {
                                if message.isLoading {
                                    ProgressView()
                                        .scaleEffect(0.7)
                                        .padding(5)
                                }
                            },
                            alignment: .bottomTrailing
                        )
                    
                    Text(getFormattedTime(from: message.timestamp))
                        .font(.caption2)
                        .foregroundColor(.gray)
                        .padding(.leading, 2)
                        .padding(.top, 2)
                }
                .frame(maxWidth: min(screenWidth * 0.9, 900), alignment: .leading) // 增大助手消息的宽度，使其更好地铺满屏幕
                
                Spacer(minLength: screenWidth * 0.02) // 减少右侧间距
            }
        }
        .padding(.horizontal, 2) // 减少水平方向的内边距
        .padding(.bottom, 8)
    }
    
    private func getFormattedTime(from date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter.string(from: date)
    }
} 